package com.woniuxy.userapp.service.impl;


import com.woniuxy.userapp.infra.model.mapper.UriMapper;
import com.woniuxy.userapp.infra.model.mapper.model.Role;
import com.woniuxy.userapp.infra.model.mapper.model.RoleUri;
import com.woniuxy.userapp.infra.model.mapper.model.Uri;
import com.woniuxy.userapp.service.RoleService;
import com.woniuxy.userapp.service.RoleUriService;
import com.woniuxy.userapp.service.UriService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-08-03
 */
@Service
public class UriServiceImpl extends ServiceImpl<UriMapper, Uri> implements UriService {

    @Autowired//角色集合
    private RoleService roleService;
    @Autowired//资源集合
    private UriService uriService;
    @Autowired//角色资源中间表集合
    private RoleUriService roleUriService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 将资源角色关系放入redis
     */
    @Override
    public void initResourceRolesMap() {
        //资源角色s集合
        Map<String, List<String>> uriRoles = new TreeMap<>();
        //查出所有角色
        List<Role> roles = roleService.list();
        List<String> AllRoleNames = roles.stream().map(item -> item.getId()+"_" + item.getRoleName()).collect(Collectors.toList());
        //查出所有资源
        List<Uri> uris = uriService.list();
        //查出角色资源中间表
        List<RoleUri> roleUris = roleUriService.list();
        redisTemplate.delete("auth:resourceRolesMap");
        for (Uri uri : uris) {
            //获取角色id集合
            Set<Integer> roleIds = roleUris.stream().filter(item -> item.getUriId().equals(uri.getId())).map(item -> item.getRoleId()).collect(Collectors.toSet());
            //获取该角色集合id对应的角色名集合
            List<String> roleNames = roles.stream().filter(item -> roleIds.contains(item.getId())).map(item -> item.getId()+"_" + item.getRoleName()).collect(Collectors.toList());
            if(roleNames.size() == 0) roleNames.addAll(AllRoleNames);
//            uriRoles.put("/"+"yoga-admin"+uri.getUrl(),roleNames);
//            System.out.println("/"+"yoga-admin"+uri.getUrl()+roleNames);
            System.out.println(uri.getUrl()+roleNames);
//            redisTemplate.opsForHash().put("auth:resourceRolesMap","/"+"yoga-admin"+uri.getUrl(),roleNames);
            redisTemplate.opsForHash().put("auth:resourceRolesMap",uri.getUrl(),roleNames);
        }
//        redisTemplate.delete("auth:resourceRolesMap");
//        redisTemplate.opsForHash().putAll("auth:resourceRolesMap",uriRoles);
    }
}
